package cn.sylinx.hbatis.ext.proxy.invoker;

import java.util.List;
import java.util.Map;

import cn.sylinx.hbatis.ext.parse.SqlParser;
import cn.sylinx.hbatis.ext.starter.util.DaoHelper;
import cn.sylinx.hbatis.kit.Tuple;

/**
 * 返回Bean对象类型
 * 
 * @author han
 *
 */
public class BeanQueryOneCommandInvoker extends AbstractQueryOneCommandInvoker {

	private String nativeSql;
	private boolean useCache;

	public BeanQueryOneCommandInvoker(String truelyDatasource, String sql, Map<String, Object> params,
			Class<?> returnType, String nativeSql, boolean useCache) {
		super(truelyDatasource, sql, params, returnType);
		this.nativeSql = nativeSql;
		this.useCache = useCache;
	}

	@Override
	public Object invoke() {

		// 使用native sql
		boolean isNativeSql = nativeSql != null && !"".equals(nativeSql.trim());

		if (isNativeSql) {

			Tuple t = SqlParser.parseSql(nativeSql, params, null);
			String truelyNativeSql = t.getObject(0);
			Object[] truelyParams = t.getObject(1);

			if (useCache) {
				return DaoHelper.create(truelyDatasource).querySqlFirstWithCache(truelyNativeSql, returnType,
						truelyParams);
			}

			List<?> dataList = DaoHelper.create(truelyDatasource).querySqlList(truelyNativeSql, returnType,
					truelyParams);
			return dataList.isEmpty() ? null : dataList.get(0);
		}

		if (useCache) {
			return DaoHelper.create(truelyDatasource).queryFirstWithCache(sql, params, returnType);
		}

		return DaoHelper.create(truelyDatasource).queryFirst(sql, params, returnType);
	}

}
